<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <!-- :to="{ path: '/' }" -->
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 主体部分 -->
        <el-card>
            <!-- gutter上下左右padding 20px -->
            <!-- 一行 可以分位24列 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" clearable v-model="userInfo.query" @clear="getUsers">
                        <el-button slot="append" icon="el-icon-search" @click="getUsers"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addUserVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <br />
            <!-- 下面是表格部分 -->
            <!-- 
                data 要展示的数据
             -->
            <el-table :data="users" border style="width: 100%" stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"> </el-table-column>
                <el-table-column prop="email" label="邮箱"> </el-table-column>
                <el-table-column prop="mobile" label="电话"> </el-table-column>
                <el-table-column prop="role_name" label="角色"> </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="{ row }">
                        <!-- {{row.msg_state?1:0}} -->
                        <!-- {{ row }} -->
                        <el-switch v-model="row.mg_state" @change="changeStatus(row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ row }">
                        <!-- v-slot="{row}" -->
                        <el-button icon="el-icon-edit" type="primary" size="mini" @click="showEditDialog(row)"></el-button>
                        <el-button icon="el-icon-delete" @click="delUsers(row.id)" type="danger" size="mini"></el-button>
                        <el-button icon="el-icon-setting" type="warning" size="mini" @click="showSetRoles(row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <br />
            <!-- 分页 -->
            <!--  @size-change="handleSizeChange" @current-change="handleCurrentChange" -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="userInfo.pagenum" :page-sizes="[1, 2, 3, 5, 10]" :page-size="userInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的弹框 -->
        <!-- :visible.sync="dialogFormVisible" true 则显示 false 则隐藏 
        :model="form" 表达管理数据-->
        <el-dialog title="添加用户" :visible.sync="addUserVisible" width="50%" @close="AddCloseHandle">
            <el-form :model="addUserForm" :rules="addUserRules" ref="addRef">
                <!-- 1.用户名 -->
                <el-form-item label="用户名" label-width="70px" prop="username">
                    <el-input v-model="addUserForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 2.密码 -->
                <el-form-item label="密码" label-width="70px" prop="password">
                    <el-input v-model="addUserForm.password" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 3.邮箱 -->
                <el-form-item label="邮箱" label-width="70px" prop="email">
                    <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 4.手机 -->
                <el-form-item label="手机" label-width="70px" prop="mobile">
                    <el-input v-model="addUserForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAdd">取 消</el-button>
                <el-button type="primary" @click="confirmAddUsers">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 编辑弹框 -->
        <el-dialog title="修改用户" :visible.sync="editUserVisible" width="50%" @close="editCloseHandle">
            <el-form :model="editUserForm" :rules="editUserRules" ref="editRef">
                <!-- 1.用户名 -->
                <el-form-item label="用户名" label-width="70px">
                    <el-input v-model="editUserForm.username" autocomplete="off" disabled></el-input>
                </el-form-item>
                <!-- 2.密码 -->
                <el-form-item label="邮箱" label-width="70px" prop="email">
                    <el-input v-model="editUserForm.email" type="password" autocomplete="off"></el-input>
                </el-form-item>
                <!-- 3.邮箱 -->
                <el-form-item label="手机" label-width="70px" prop="mobile">
                    <el-input v-model="editUserForm.mobile" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmEdit">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 分配角色 -->
        <el-dialog title="分配角色" :visible.sync="setRolesVisible" width="50%">
            <p>当前用户：{{ currentRoles.username }}</p>
            <p>当前角色：{{ currentRoles.role_name }}</p>
            <div>
                <!-- :label="item.roleName" 显示的内容 
                :value="item.id" 数据id 
                v-model="value" 被选择角色的id -->
                分配角色：
                <el-select v-model="value" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.id"
                     :label="item.roleName" :value="item.id">
                    </el-option>    
                </el-select>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button>取 消</el-button>
                <el-button type="primary" @click="getVal">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    getUsers,
    addUsers,
    putStatus,
    editUsers,
    delUsers,
    getRoles
} from "@/api/user.js";
export default {
    name: "users-com",
    data() {
        // rule 校验规则对象 val输入的内容 cb 回调函数
        const checkEmail = (rule, val, cb) => {
            let reg = /^\w+\@\w+\.(com|cn|net)$/;
            if (reg.test(val)) {
                return cb(); //执行回调函数
            }
            cb(new Error("邮箱格式不正确!"));
        };
        // 自定义校验手机号码
        const checkMobile = (rule, val, cb) => {
            let reg = /^1[3-9]\d{9}$/;
            if (reg.test(val)) {
                return cb(); //执行回调函数
            }
            cb(new Error("手机号码格式不正确!"));
        };
        return {
            userInfo: {
                query: "", //搜索的数据
                pagenum: 1, //页码
                pagesize: 3, //每页请求几条数据
            },
            total: 0,
            pagenum: 1,
            users: [], // 储存数据的地方
            // ---添加用户的弹框数据------------
            addUserVisible: false,
            addUserForm: {
                username: "",
                password: "",
                email: "",
                mobile: "",
            },
            // 校验 添加表单
            addUserRules: {
                username: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { min: 3, max: 6, message: "格式不正确", trigger: "blur" },
                ],
                password: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { min: 6, max: 12, message: "格式不正确", trigger: "blur" },
                ],
                email: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { validator: checkEmail, trigger: "blur" },
                ],
                mobile: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur" },
                ],
            },
            // 编辑框的内容
            editUserVisible: false,
            editUserForm: {
                username: "",
                id: "",
                email: "",
                mobile: "",
            },
            editUserRules: {
                email: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { validator: checkEmail, trigger: "blur" },
                ],
                mobile: [
                    { required: true, message: "必填项!", trigger: "blur" },
                    { validator: checkMobile, trigger: "blur" },
                ],
            },
            // 是否展示分批角色
            setRolesVisible: false,
            currentRoles: {}, //当前的角色对象
            options: [],
            value: ''
        };
    },
    created() {
        this.getUsers();
    },
    methods: {
        async getUsers() {
            // 1. 请求数据
            let {
                data: { data, meta },
            } = await getUsers(this.userInfo);
            // 2.判断数据是否请求成功
            if (meta.status != 200) return this.$message("用户数据请求失败!");
            this.total = data.total; //总数据条数
            this.pagenum = data.pagenum; //当前页码
            this.users = data.users; //展示的数据
            console.log(data, 111);
        },
        // 数据条数发送改变的时候 触发
        handleSizeChange(size) {
            this.userInfo.pagesize = size;
            this.getUsers();
        },
        // 页码发送改变的时候触发
        handleCurrentChange(page) {
            this.userInfo.pagenum = page;
            this.getUsers();
        },
        // 点击 添加弹框的确认按钮
        confirmAddUsers() {
            this.$refs.addRef.validate(async (isOK) => {
                // 1. 如果校验失败 则  提示
                if (!isOK) return this.$message.error("表单校验失败!");
                //2. 成功
                let {
                    data: { meta },
                } = await addUsers(this.addUserForm);
                // 3. 如果提交失败 则
                if (meta.status != 201) return this.$message.error("提交失败，请重试!");
                // 4. 如果提交成功则更新数据
                this.getUsers();
                //5 移出校验结果 和输入内容
                this.$refs.addRef.resetFields();
                // 6. 隐藏 弹框
                this.addUserVisible = false;
            });
        },
        // 点击取消按钮 重置表单;
        cancelAdd() {
            // 移出校验结果 和输入内容
            this.$refs.addRef.resetFields();
            // 关闭弹框
            this.addUserVisible = false;
        },
        // 点击添加弹框的  x 号的时候
        AddCloseHandle() {
            this.$refs.addRef.resetFields();
            console.log("触发了close方法 AddCloseHandle");
        },
        // 点击状态 触发
        async changeStatus(row) {
            console.log(row, row.id, row.mg_state);
            let {
                data: { meta },
            } = await putStatus(row.id, row.mg_state);
            if (meta.status != 200) return this.$message.error("修改状态失败!");
            this.$message.success("修改状态成功!");
        },
        // 点击编辑按钮 触发
        showEditDialog(row) {
            // 回显
            this.editUserForm = row;
            // 显示数据
            this.editUserVisible = true;
        },
        // 点击 编辑弹框的 X 号触发
        editCloseHandle() {
            this.editUserVisible = false;
        },
        // 点击 确定修改按钮 触发;
        async confirmEdit() {
            // 1.请求数据
            let {
                data: { meta },
            } = await editUsers(this.editUserForm);
            // 2.如果请求失败 则 弹出提示
            if (meta.status != 200) return this.$message("修改失败!");
            // 3. 请求成功 则弹出提示
            this.$message.success("修改成功!");
            // 4. 更新数据
            this.getUsers(); //更新数据
            // 5.关闭弹框
            this.editUserVisible = false;
        },
        async delUsers(id) {
            let res = await this.$confirm(
                "此操作将永久删除该文件, 是否继续?",
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }
            ).catch((err) => err);
            if (res == "cancel") return this.$message("您取消了删除!");

            let {
                data: { meta },
            } = await delUsers(id);
            if (meta.status != 200) return this.$message("删除失败!");
            this.$message.success("删除成功!");
            this.getUsers(); //更新数据
        },
        // 点击设置按钮 触发
        async showSetRoles(row) {
            this.currentRoles = row // 留着角色信息
            this.setRolesVisible = true // 展示弹框
            // 发起请求
            let { data: { data, meta } } = await getRoles()
            // 判断
            if (meta.status != 200) return this.$message("请求失败")
            // 赋值
            this.options = data
        },
        getVal(){
            console.log(this.value , 10001);
        }
    },
};
</script>
<style scoped lang="scss">
::v-deep .el-breadcrumb__inner {
    font-size: 12px !important;
}

::v-deep .el-card {
    margin-top: 15px;
}
</style>
